﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Net;

namespace HyperV
{
    public class Host
    {
        private string address;
        private Credentials credentials;

        public Host(string address, Credentials credentials)
        {
            this.address = address;
            this.credentials = credentials;
        }

        public Host()
        {
            this.address = ".";
            this.credentials = null;
        }

        public List<Guest> Guests
        {
            get
            {
                try
                {
                    ConnectionOptions connOpts = new ConnectionOptions();
                    if (credentials != null)
                    {
                        connOpts.Username = credentials.Username;
                        connOpts.Authority = "ntlmdomain:" + credentials.Domain;
                        connOpts.SecurePassword = credentials.Password;
                    }
                    ManagementScope manScope;
                    if (address == ".")
                        manScope = new ManagementScope(String.Format(@"\\{0}\root\virtualization", address));
                    else
                        manScope = new ManagementScope(String.Format(@"\\{0}\root\virtualization", address, connOpts));
                    ObjectQuery queryObj = new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
                    ManagementObjectSearcher vmSearcher = new ManagementObjectSearcher(manScope, queryObj);
                    ManagementObjectCollection vmCollection = vmSearcher.Get();
                    var result = new List<Guest>(vmCollection.Count);
                    foreach (ManagementObject vm in vmCollection)
                    {
                        result.Add(new Guest(vm["ElementName"].ToString(), this));
                    }
                    return result;
                }
                catch (Exception)
                {
                }
                return new List<Guest>();
            }
        }

        public Credentials Credentials
        {
            get
            {
                return credentials;
            }
        }

        public string Address
        {
            get
            {
                return address;
            }
        }

    }
}
